package com.fbms.module.auth.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import com.fbms.common.constants.CacheConstants;
import com.fbms.common.constants.Constants;
import com.fbms.module.auth.Bean.LoginUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 类描述：TODO
 *
 * @ClassName TokenService
 * @Author HappyBoy
 * @Date 2023-03-24 15:40
 **/
@Component
public class TokenService {

    protected static final long MILLIS_SECOND = 1000;
    /**
     * Redis缓存
     */
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 创建Token
     * @param loginUser 登录用户
     * @return 结果
     */
    public LoginUserDTO createToken(LoginUserDTO loginUser){
        String token = UUID.fastUUID().toString(true);
        loginUser.setToken(token);
        // 将Token保存到redis中
        refreshToken(loginUser);
        return loginUser;
    }

    private void refreshToken(LoginUserDTO loginUser) {
        String cacheKey = getTokenKey(loginUser.getToken());

        Map<String, Object> userMap = BeanUtil.beanToMap(loginUser, new HashMap<>(),
                CopyOptions.create().setIgnoreCase(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));

        redisTemplate.opsForHash().putAll(cacheKey, userMap);

        long LOGIN_USER_TTL = System.currentTimeMillis() + Constants.TOKEN_EXPIRE * MILLIS_SECOND;
        // 防止无效用户 设置用户有效期
        redisTemplate.expire(cacheKey, LOGIN_USER_TTL, TimeUnit.SECONDS);
    }

    private String getTokenKey(String token)
    {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }

}
